import { createSlice, PayloadAction } from '@reduxjs/toolkit';

/**
 * UI状态管理接口
 *
 * 管理用户界面相关的状态，包括布局、主题、加载状态、通知等
 */
interface UiState {
  /** 侧边栏是否折叠 */
  sidebarCollapsed: boolean;
  /** 当前选中的菜单项 */
  selectedMenuKey: string;
  /** 主题模式 */
  theme: 'light' | 'dark';
  /** 加载状态管理 */
  loading: {
    global: boolean;
    [key: string]: boolean;
  };
  /** 通知消息列表 */
  notifications: Array<{
    id: string;
    type: 'success' | 'error' | 'warning' | 'info';
    message: string;
    timestamp: number;
  }>;
}

/**
 * 初始UI状态
 */
const initialState: UiState = {
  sidebarCollapsed: false,
  selectedMenuKey: '1',
  theme: 'light',
  loading: {
    global: false,
  },
  notifications: [],
};

/**
 * UI状态管理Slice
 *
 * 管理用户界面相关的状态和操作
 */
const uiSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    /** 设置侧边栏折叠状态 */
    setSidebarCollapsed: (state, action: PayloadAction<boolean>) => {
      state.sidebarCollapsed = action.payload;
    },
    /** 设置当前选中的菜单项 */
    setSelectedMenuKey: (state, action: PayloadAction<string>) => {
      state.selectedMenuKey = action.payload;
    },
    /** 设置主题模式 */
    setTheme: (state, action: PayloadAction<'light' | 'dark'>) => {
      state.theme = action.payload;
    },
    /** 设置特定组件的加载状态 */
    setLoading: (state, action: PayloadAction<{ key: string; loading: boolean }>) => {
      state.loading[action.payload.key] = action.payload.loading;
    },
    /** 设置全局加载状态 */
    setGlobalLoading: (state, action: PayloadAction<boolean>) => {
      state.loading.global = action.payload;
    },
    /** 添加通知消息 */
    addNotification: (state, action: PayloadAction<Omit<UiState['notifications'][0], 'id' | 'timestamp'>>) => {
      const notification = {
        ...action.payload,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        timestamp: Date.now(),
      };
      state.notifications.push(notification);

      // 限制通知数量，保持最新的10条
      if (state.notifications.length > 10) {
        state.notifications = state.notifications.slice(-10);
      }
    },
    /** 移除指定通知 */
    removeNotification: (state, action: PayloadAction<string>) => {
      state.notifications = state.notifications.filter(n => n.id !== action.payload);
    },
    /** 清除所有通知 */
    clearNotifications: (state) => {
      state.notifications = [];
    },
  },
});

export const {
  setSidebarCollapsed,
  setSelectedMenuKey,
  setTheme,
  setLoading,
  setGlobalLoading,
  addNotification,
  removeNotification,
  clearNotifications,
} = uiSlice.actions;

export default uiSlice.reducer;